package spark.network;

import org.apache.log4j.Logger;
import spark.network.protocol.Base;
import spark.network.protocol.Response;

import java.util.HashMap;
import java.net.InetSocketAddress;

/**
 * An active player known to the server (not necessarily logged in).
 */
public class NetworkConnection {
	private static Logger logger = Logger.getLogger(NetworkConnection.class);

	public static final long SESSION_UNESTABLISHED = -1;

	private long session = SESSION_UNESTABLISHED;
	private InetSocketAddress address;
	private InetSocketAddress responseAddress;
	private HashMap<Long, BufferedPacket<Response>> bufferedResponses = new HashMap<Long, BufferedPacket<Response>>();

	public NetworkConnection() {
	}

	public NetworkConnection(long session, InetSocketAddress address, InetSocketAddress responseAddress) {
		this.session = session;
		this.address = address;
		this.responseAddress = responseAddress;
	}

	public InetSocketAddress getAddress() {
		return address;
	}

	public void setAddress(InetSocketAddress address) {
		this.address = address;
	}

	public InetSocketAddress getResponseAddress() {
		return responseAddress;
	}

	public void setResponseAddress(InetSocketAddress responseAddress) {
		this.responseAddress = responseAddress;
	}

	public long getSession() {
		return session;
	}

	public void setSession(long session) {
		this.session = session;
	}

	/**
	 * Buffers a response for possible later use if it has to be resend.
	 *
	 * @param response Response to buffer.
	 */
	public void bufferResponse(Response response) {
		BufferedPacket<Response> bufferedResponse = new BufferedPacket<Response>(response);
		bufferedResponses.put(response.getResponseToId(), bufferedResponse);
	}

	/**
	 * Obtains the corresponding response to the query.
	 *
	 * @param query Query to which a response should be found.
	 * @return Corresponding response or null of none was found.
	 */
	public BufferedPacket<Response> getBufferedResponse(Base query) {
		return bufferedResponses.get(query.getPacketId());
	}

	/**
	 * Resets the connection to a state equal of that it would have after creating a new NetworkConnection using
	 * the default constructor.
	 */
	public void reset() {
		session = SESSION_UNESTABLISHED;
		address = null;
		responseAddress = null;
		bufferedResponses.clear();
	}
}
